package com.moduls.interfaceFunction.weixin.pay;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.moduls.interfaceFunction.core.Result;
import com.moduls.interfaceFunction.weixin.pay.utils.GetWxOrderno;
import com.moduls.interfaceFunction.weixin.pay.utils.RequestHandler;
import com.moduls.interfaceFunction.weixin.pay.utils.Sha1Util;
import com.moduls.interfaceFunction.weixin.pay.utils.TenpayUtil;

import net.sf.json.JSONObject;


public class WeixinPay  {
	public  String appid = "wx67101a68f7aec725";//在微信开发平台登记的app应用
	public  String appsecret = "c65e02727ebf7447210e4d93b16cf392";
	public  String partner = "1509935681";//商户号
	public  String partnerkey ="f11478723a32463f97348c2d5739a1a7";//不是商户登录密码，是商户在微信平台设置的32位长度的api秘钥，
	public  String createOrderURL="https://api.mch.weixin.qq.com/pay/unifiedorder";
	public  String backUri="http://XXXXXXXX/api/weixin/topay.jhtml";//微信支付下单地址
	public  String notifyurl="http://121.42.231.1:8180/wx/wxapijava/wxcallback";//异步通知地址
//	JSONObject retMsgJson=new JSONObject();  
//	
//	 String json=retMsgJson.toString();                   
   
	 
	//获取微信支付信息
	public  Result getpaystring(String reward_no,String money,HttpServletRequest request,HttpServletResponse response) throws SQLException, UnknownHostException {
		
//		if (usertype.equals("1")) {
//			appid="wx5e1c493b404bc91f";
//			appsecret="0acfb1191be6b6d7e632e8573c240f21";
//			partner="1450986502";
//			partnerkey="beijingqiuyibaodiandeyizhibao666";
//		}
	
	  // String strOid=orderdetail.get("order_id").toString();
		//金额转化为分为单位
				float sessionmoney = Float.parseFloat(money);
				String finalmoney = String.format("%.2f", sessionmoney);
				finalmoney = finalmoney.replace(".", "");
						String currTime = TenpayUtil.getCurrTime();
						//8位日期
						String strTime = currTime.substring(8, currTime.length());
						//四位随机数
						String strRandom = TenpayUtil.buildRandom(10) + "";
						//10位序列号,可以自行调整。
						String strReq = strTime + strRandom;		
						//商户号
						String mch_id = partner;
						//子商户号  非必输
						//String sub_mch_id="";
						//设备号   非必输
						String device_info="";
						//随机数 
						String nonce_str = strReq;
						String body =reward_no;
						//附加数据
//						String attach =orderdetail.get("creator_id").toString() ;
						//商户订单号
						String out_trade_no =reward_no; //strOid+"|"+System.currentTimeMillis();//订单编号加时间戳
						int intMoney = Integer.parseInt(finalmoney);			
						//总金额以分为单位，不带小数点
						String total_fee = String.valueOf(intMoney);
						//订单生成的机器 IP
						InetAddress ia=null;
						ia=ia.getLocalHost();
						String localip=ia.getHostAddress();
						String spbill_create_ip =localip;
			            String notify_url =notifyurl;//微信异步通知地址			
						String trade_type = "APP";//app支付必须填写为APP
			                        //对以下字段进行签名
			            SortedMap<String, String> packageParams = new TreeMap<String, String>();
						packageParams.put("appid", appid);  
//						packageParams.put("attach", attach); 
						packageParams.put("body", body);  
						packageParams.put("mch_id", mch_id);  	
						packageParams.put("nonce_str", nonce_str);  
						packageParams.put("notify_url", notify_url);  
						packageParams.put("out_trade_no", out_trade_no);  	
						packageParams.put("spbill_create_ip", spbill_create_ip); 
						packageParams.put("total_fee", total_fee);
						packageParams.put("trade_type", trade_type);  
						 RequestHandler reqHandler = new RequestHandler(request, response);  
						//RequestHandler reqHandler = new RequestHandler();
						 
						 reqHandler.init(appid, appsecret, partnerkey);        
				            String sign = reqHandler.createSign(packageParams);//获取签名  
				            
						String xml="<xml>"+
								"<appid>"+appid+"</appid>"+
//								"<attach>"+attach+"</attach>"+
								"<body><![CDATA["+body+"]]></body>"+
								"<mch_id>"+mch_id+"</mch_id>"+
								"<nonce_str>"+nonce_str+"</nonce_str>"+
								"<notify_url>"+notify_url+"</notify_url>"+
								"<out_trade_no>"+out_trade_no+"</out_trade_no>"+
								"<spbill_create_ip>"+spbill_create_ip+"</spbill_create_ip>"+
								"<total_fee>"+total_fee+"</total_fee>"+
								"<trade_type>"+trade_type+"</trade_type>"+
								"<sign>"+sign+"</sign>"+
								"</xml>";
						String allParameters = "";
						try {
							allParameters =  reqHandler.genPackage(packageParams);
						 } catch (Exception e) {

							e.printStackTrace();
						}
						//String createOrderURL = createOrderURL;
						String prepay_id= new GetWxOrderno().getPayNo(createOrderURL, xml);
					

			           SortedMap<String, String> finalpackage = new TreeMap<String, String>();
						String timestamp = Sha1Util.getTimeStamp();
						finalpackage.put("appid", appid);  
						finalpackage.put("timestamp", timestamp);  
						finalpackage.put("noncestr", nonce_str);  
						finalpackage.put("partnerid", partner); 
						finalpackage.put("package", "Sign=WXPay");  			
						finalpackage.put("prepayid", prepay_id);  
			  			String finalsign = reqHandler.createSign(finalpackage);
			  			Result result=new Result();
			  			Map<String,Object> map=new HashMap<>();
			  			map.put("msg", "ok");
			  			map.put("appid", appid);
			  			map.put("timestamp", timestamp);
			  			map.put("noncestr", nonce_str);
			  			map.put("partnerid", partner);
						map.put("prepayid", prepay_id);
						map.put("package", "Sign=WXPay");
						map.put("packageName", "Sign=WXPay");
						map.put("sign", finalsign);
						result.setResult(map);	
						result.setMessage("ok");
						result.setStatus(1); 
						return result;
		
	}
}


